 package org.leumasjaffe.math.probability;

import java.util.Random;

import org.eclipse.jdt.annotation.NonNull;

import flanagan.analysis.Stat;


public class BinomialRV extends BernoulliRV {
		
	private final int n;
	
	public BinomialRV(double p) {
		super(p);
		this.n = 1;
	}
	
	public BinomialRV(int n, double p) {
		super(p);
		this.n = n;
	}
	
	public BinomialRV(@NonNull Random r, double p) {
		super(r, p);
		this.n = 1;
	}
	
	public BinomialRV(@NonNull Random r, int n, double p) {
		super(r, p);
		this.n = n;
	}

	@Override
	public double getEV() {
		return this.n*super.getEV();
	}

	@Override
	public double getVar() {
		return this.n*super.getEV();
	}

	@Override
	public double getP(int x) {
		if (x >=0 && x <= this.n)
			return Stat.binomialCoeff(this.n, x) * Math.pow(this.p, x) * Math.pow(1 - this.p, this.n - x);
		return 0;
	}

	@Override
	public double calcX(double p) {
		if (!isProb(p)) throw new IllegalArgumentException("Arguement is not a valid probability");
		double u = 0;
		int x = 0;
		while (u<p) {
			x++;
			u += getP(x);
		}
		return x;
	}
	
	@Override
	public double getF(int x) {
		if (x < 0)
			return 0;
		else if (x >= this.n)
			return 1;
		return Stat.regularisedBetaFunction(this.n-x, x+1, 1-this.p);
	}

}
